/*
 * @Author: Choisaaaa
 * @Date: 2018/5/3  22:47
 * 添加或者编辑商品 组件
 */

import React from "react";
import "./product-save.scss";
import Footer from "component/footer/footer.jsx";           //页尾子组件
import PageTitle from 'component/page-title/page-title.jsx';//页面标题子组件
import CategorySelector from './category-selector.jsx';     //商品种类下拉框子组件
import FileUploader from 'util/file-uploader/index.jsx';    //图片上传子组件
import RichEditor from 'util/rich-editor/rich-editor.jsx';  //富文本控件子组件
import MUtil from 'util/mm.jsx';
import Product from 'service/product-service.jsx'

const _product = new Product();
const _mm = new MUtil();

class ProductSave extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            id :  this.props.match.params.pid,  //商品ID
            productName : "",                          //商品名称:通过方法 1 保存
            productSubtitle : "",                      //商品子标题:通过方法 1 保存
            categoryId : 0,                     //商品所属一级种类ID:通过方法 2 保存
            parentCategoryId : 0,               //商品所属二级种类ID:通过方法 2 保存
            normalPrice : "",                         //价格:通过方法 1 保存
            promotionPrice : "",                         //价格:通过方法 1 保存
            productStock : "",                         //库存:通过方法 1 保存
            subImgsAddr : [],                     //商品图片:通过方法 3 保存
            productDesc : ""  ,                      //富文本控价输入的字段:通过方法 6 保存
            enableStatus : 2                          //商品状态1为在售
        };
    }
    componentDidMount(){
        this.loadProductList();
    }
    componentWillMount(){//组件将要加载
        this.mounted = true;
    }
    componentWillUnmount(){//组件销毁
        this.mounted = false;
    }
    loadProductList(){//编辑商品时信息回填
        if(this.state.id){
            _product.getProduct(this.state.id).then((res)=>{
                let images = res.subImgsAddr.split(",");
                res.subImgsAddr = images.map((imgUri) =>{
                    return{
                        uri: imgUri,
                        url: res.imageHost + imgUri
                    }
                });
                res.defaultDetail = res.productDesc;
                if(this.mounted){
                    this.setState(res)
                }
            },(errMsg)=>{
                _mm.errorTips(errMsg)
            });
        }

    }
    onValueChange(e){//方法1.保存商品名称，描述，单价，库存的值
        let name = e.target.getAttribute("name"),
            value = e.target.value;
        this.setState({
            [name] : value
        });
    }
    onCategoryChange(categoryId, parentCategoryId){//方法2.品类选择器发生变化
        this.setState({
            categoryId          : categoryId,
            parentCategoryId    : parentCategoryId
        });
    }
    onUploadSuccess(res){//方法3.图片上传成功，将服务响应回来的图片地址保存到数组中
        let subImages = this.state.subImgsAddr;
        var image = {
            url : res[0].url,
            uri : res[0].uri
        }
        subImages.push(image);
        this.setState({
            subImgsAddr : subImages
        });
    }
    onUploadError(errMsg){//方法4.图片上传失败
        _mm.errorTips(errMsg)
    }
    onImageDelete(e){//方法5.删除上传的图片
        let index = e.target.getAttribute("index");
        let subImages = this.state.subImages;
        subImages.splice(index,1);
        this.setState({
            subImages : subImages
        });
    }
    onDetailValueChange(value){//方法6.富文本控件的输入值改变
        this.setState({
            detail : value
        });
    }
    onSubmit(){//方法7.提交按钮响应事件
        let product = {
                productName : this.state.productName,
                productSubtitle : this.state.productSubtitle,
                categoryId : parseInt(this.state.categoryId),
                subImgsAddr   : this.getSubImagesString(),
                productDesc      : this.state.productDesc,
                normalPrice       : parseFloat(this.state.normalPrice),
                promotionPrice       : parseFloat(this.state.promotionPrice),
                productStock       : parseInt(this.state.productStock),
                enableStatus      : this.state.enableStatus
            },
            productCheckResult = _product.checkProduct(product);
        if(productCheckResult.status){//表单验证通过
            _product.saveProduct(product).then((res)=>{
                _mm.successTips(res);
            },(errMsg)=>{
                _mm.errorTips(errMsg)
            });
        }else{
            _mm.errorTips(productCheckResult.msg);
        }
    }
    getSubImagesString (){//将数据元素拼接成String返回
        return this.state.subImgsAddr.map((image) =>image.uri).join(",");
    }
    render(){
        return (
            <div id="page-wrapper">
                <PageTitle title={
                    this.state.id ? "编辑商品" : "添加商品"
                }/>
                <div className="form-horizontal">
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品名称</label>
                        <div className="col-md-5">
                            <input type="text" className="form-control"
                                   placeholder="请输入商品名称"
                                   name="productName"
                                   value={this.state.productName||""}
                                   onChange={(e) => this.onValueChange(e)}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品描述</label>
                        <div className="col-md-5">
                            <input type="text" className="form-control"
                                   placeholder="请输入商品描述"
                                   name="productSubtitle"
                                   value={this.state.productSubtitle||""}
                                   onChange={(e) => this.onValueChange(e)}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">所属分类</label>
                        <CategorySelector
                            categoryId={this.state.categoryId}
                            parentCategoryId={this.state.parentCategoryId}
                            onCategoryChange = {(categoryId, parentCategoryId) => this.onCategoryChange(categoryId, parentCategoryId)} />
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品原价</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control"
                                       placeholder="价格"
                                       name="normalPrice"
                                       value={this.state.normalPrice||""}
                                       onChange={(e) => this.onValueChange(e)}/>
                                <span className="input-group-addon">元</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品售价</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control"
                                       placeholder="价格"
                                       name="promotionPrice"
                                       value={this.state.promotionPrice||""}
                                       onChange={(e) => this.onValueChange(e)}/>
                                <span className="input-group-addon">元</span>
                            </div>
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品库存</label>
                        <div className="col-md-3">
                            <div className="input-group">
                                <input type="number" className="form-control"
                                       placeholder="库存"
                                       name="productStock"
                                       value={this.state.productStock||""}
                                       onChange={(e) => this.onValueChange(e)}/>
                                <span className="input-group-addon">件</span>
                            </div>

                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品图片</label>
                        <div className="col-md-10">
                            {
                                this.state.subImgsAddr.length
                                    ? this.state.subImgsAddr.map((image,index) =>
                                    (<div className="img-con" key={index}>
                                        <img src={image.url} alt="商品图片" className="img"/>
                                        <i className="fa fa-close" index={index} onClick={(e) => this.onImageDelete(e)} />
                                    </div>)
                                )  : (<div className="choose-img">请上传图片</div>)
                            }
                        </div>
                        <div className="col-md-offset-2 col-md-10 file-upload-con">
                            <FileUploader onSuccess={(res)=>this.onUploadSuccess(res)}
                                          onError={(errMsg) => this.onUploadError(errMsg)}
                                          maxFiles = "6"
                            />
                        </div>
                    </div>
                    <div className="form-group">
                        <label className="col-md-2 control-label">商品详情</label>
                        <div className="col-md-10">
                            <RichEditor
                                detail={this.state.productDesc}
                                defaultDetail={this.state.defaultDetail}
                                onValueChange = {(value) => this.onDetailValueChange(value)}/>
                        </div>
                    </div>
                    <div className="form-group">
                        <div className="col-md-offset-2 col-md-10">
                            <button type="submit" className="btn btn-primary btn-lg"
                                    onClick={(e) => {this.onSubmit(e)}}><i className="fa fa-paper-plane"/> 提交</button>
                        </div>
                    </div>
                </div>
                <Footer/>
            </div>
        );
    }
}

export default ProductSave;